package com.company;

class MyThread implements Runnable {
    private int ticket = 1000;
//    @Override
//    public void run() {
//        while (true) {
//            // 性能降低了，且有一个线程占用时间过长
//            synchronized (this) {
//                if (this.ticket > 0) {
//                    try {
//                        Thread.sleep(100); // 模拟网络延时
//                    } catch (InterruptedException e) {
//                        e.printStackTrace();
//                    }
//                    System.out.println(Thread.currentThread().getName() + " is selling ticket, and ticket remain " + (this.ticket--));
//                } else {
//                    System.out.println("****tickets are all sold***");
//                    break;
//                }
//            }
//        }
//    }

    protected synchronized void sale() {
        while (true) {
            if (this.ticket > 0) {
                try {
                    Thread.sleep(100); // 模拟网络延时
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + " is selling ticket, and ticket remain " + (this.ticket--));
            } else {
                System.out.println("****tickets are all sold***");
                break;
            }
        }
    }

    @Override
    public void run() {
        this.sale();
    }
}

/**
 * @date 2020-06-08 19:46 同步问题的解决方案
 */
public class ThreadSynchronized {
    public static void main(String[] args) throws Exception {
        Runnable mt = new MyThread();

        for (int x = 0; x < 3; x++) {
            Thread th = new Thread(mt, "thread + " + (x + 1));
            th.start();
        }
    }
}
